package com.order.app;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

/**
 * @author xiangminwen
 * @date 2024/11/25 16:21
 */
public class LockBasedQueue2 {

    private final Queue<Object> queue = new LinkedList<>();
    private final Object synObj = new Object();

    public void put(Object element) throws InterruptedException {
        synchronized (synObj) {
            while (queue.size() == 2) {
                System.out.println("111");
                synObj.wait();
                System.out.println("112");
            }
            System.out.println("113");
            queue.offer(element);
            synObj.notify();
        }
    }

    public Object take() throws InterruptedException {
        synchronized (synObj) {
            while (queue.isEmpty()) {
                synObj.wait();
            }
            Object element = queue.poll();
            synObj.notify();
            return element;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockBasedQueue2 basedQueue = new LockBasedQueue2();
        new Thread(() -> {
            try {
                basedQueue.put("22221");
                basedQueue.put("22221");
            } catch (InterruptedException ignored) {
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                basedQueue.put("22222");
                basedQueue.put("22222");
            } catch (InterruptedException ignored) {
            }
        }, "t2").start();

        new Thread(() -> {
            try {
                basedQueue.put("22223");
                basedQueue.put("22223");
            } catch (InterruptedException ignored) {
            }
        }, "t3").start();
        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            try {
                System.out.println(basedQueue.take());
            } catch (InterruptedException ignored) {
            }
        }, "t4").start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println(basedQueue.queue.size());

/*        new Thread(() -> {
            try {
                System.out.println(basedQueue.take());
                System.out.println(basedQueue.take());
                System.out.println(basedQueue.take());
                System.out.println(basedQueue.take());
                System.out.println(basedQueue.take());
            } catch (InterruptedException ignored) {
            }
        }, "t4").start();*/
        TimeUnit.SECONDS.sleep(1);
        System.out.println(basedQueue.queue.size());
    }
}
